package com.xiaoshou.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.xiaoshou.pojo.Question;
import com.xiaoshou.pojo.User;

@Repository
public class QuestionDao extends BaseDao<Question, String> {

	public void saveNewQuestion(Question q) {
		String hql = "insert into question values(:id,:questionname,:createtime,:updatetime,:questiontypeid,:userid)";
		Query query = getSession().createSQLQuery(hql);
		query.setParameter("id", q.getId());
		query.setParameter("questionname", q.getQuestionname());
		query.setParameter("userid", q.getUser().getId());
		query.setParameter("createtime", q.getCreatetime());
		query.setParameter("updatetime", q.getUpdatetime());
		query.setParameter("questiontypeid", q.getQuestiontype().getId());
		query.executeUpdate();

	}

	public List<Question> findAllQuestion() {
		String hql = "from Question order by updatetime desc";
		Query query = getSession().createQuery(hql);
		@SuppressWarnings("unchecked")
		List<Question> list = query.list();
		return list;
	}

	public void updateQuestion(Question q) {
		String sql = "UPDATE question set questionname=:questionname,updatetime=:updatetime where id=:id";
		Query query = getSession().createSQLQuery(sql);
		query.setParameter("questionname", q.getQuestionname());
		query.setParameter("updatetime", q.getUpdatetime());
		query.setParameter("id", q.getId());
		query.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public List<Question> findByNowPage(int nowPage) {
		String hql = "from Question order by updatetime desc";
		Query query = getSession().createQuery(hql);
		// query.setFetchSize(nowPage);
		query.setFirstResult(nowPage * 10);
		query.setMaxResults(10);
		return query.list();
	}

	public List<Question> findQuestionsTrendsBySales(User user) {
		System.out.println(user);
		if(user!=null){
			
			/*String sql = "SELECT * FROM question q LEFT JOIN answers a ON q.id=a.questionid where q.userid=:userid ORDER BY q.updatetime DESC,a.updatetime desc";
			Query query = getSession().createSQLQuery(sql);
			query.setParameter("userid", user.getId());
			@SuppressWarnings("unchecked")
			List<Question> salesQuestionTrendsList = query.list();
			return salesQuestionTrendsList;*/
			
			String hql = "from Question q inner join fetch q.answerses a  where q.user=:currentUser ORDER BY q.updatetime DESC,a.updatetime DESC limit 0,10";
			//on q = a.question
			Query query = getSession().createQuery(hql);
			query.setParameter("currentUser", user);
			@SuppressWarnings("unchecked")
			List<Question> salesQuestionTrendsList = query.list();
			return salesQuestionTrendsList;
		}else {
			return null;
		}
	}

}
